<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/04/29
 * Time: 10:22
 */
namespace app\mini\controller;
use app\common\Code;
use app\common\exception\UploadException;
use app\common\library\exception\ApiException;
use app\common\library\MemberVo;
use app\common\library\Upload;
use app\common\model\Amap;
use app\common\traits\ControllerCheckValidate;
use app\common\traits\InterfacesExceptionTrait;
use think\Cache;
use think\Config;
use think\Controller;
use think\Env;
use think\Exception;


/**
 * API模块 公共的控制器
 * Class Common
 */
class Common extends Controller
{
    use ControllerCheckValidate, InterfacesExceptionTrait;

    protected static $http_code = 500; //http 错误代号
    protected static $err_code = 0; //http 错误代号

    /**
     * headers信息
     * @var string
     */
    public $headers = '';
    public $member_info_arr = [];
    public $page = 1;
    public $size = 10;
    public $from = 0;
    public $img_sec_check = '非法图片，请重新上传';
    /**
     * 初始化的方法
     */
    public function _initialize()
    {
        $action = request()->action(true);
//        $this->member_info_arr = ['member_id' => 1, 'role_id' => 1, 'token' => '', 'openid' => 'os9TX5dRwy94qkTRlWUen4dDoQ-8', 'default_shop_id' => 1, 'member_type' => 1];
        $actions = ['login', 'order_wechat_notify', 'recharge_notify'];
        if (!in_array($action, $actions)) {
            $this->checkToken();
            $this->setMemberInfo();

        }
        $this->checkShopModule(); // 商家模块验证
        $this->validateRun();     // 验证器自动验证
    }

    public function checkShopModule()
    {
        $module = explode('/', request()->path())[2];
        if($module === 'shop' && MemberVo::instance()->getShopId() === 0) {
            throw new ApiException('您不是商家，无权调用该接口');
        }
    }

    public function setMemberInfo() {
        $memberVo = MemberVo::instance();
        $memberVo->setMemberId($this->member_info_arr['member_id']);
        $memberVo->setMemberType($this->member_info_arr['member_type'] ?? 0);
        $memberVo->setMiniOpenId($this->member_info_arr['mini_openid'] ?? '');
        $memberVo->setShopId($this->member_info_arr['default_shop_id'] ?? 0);
        $memberVo->setToken($this->member_info_arr['token'] ?? '');
    }

    /**
     * 检测token
     */
    public function checkToken()
    {
        $token = input('token','');
        if (empty($token)){
            throw new ApiException('token不能为空', 200,1001);
        }
        $info_str = Cache::store('redis')->get($token);
        if (empty($info_str)){
            throw new ApiException('token已过期请重新登录',200,1001);
        }
        $user_info = json_decode($info_str,true);
        $this->member_info_arr = $user_info;
    }

    /**
     * @param $handleResult
     * @param int $code
     * @param array $meta
     * @return \think\response\Json
     */
    protected function response($handleResult, array $meta = [], int $code = Code::DEFAULT_CODE)
    {
        $msg = 'success';
        $options = [];
        if ($handleResult == false) {
            if ($this->haveError()) {
                list($code, $msg) = $this->getFirstError();
                $httpCode = $this->getHttpCode();
            }
            $handleResult = [];
            $options = ['json_encode_param' => JSON_FORCE_OBJECT];
        }
        $data = [
            'code' => $code,
            'message' => $msg,
            'data' => $handleResult
        ];
        if(!empty($meta)) $data['meta'] = $meta;
        return json($data, $httpCode ?? $code,[],$options);
    }

    /**
     * 文件上传公共方法
     * @return \think\response\Json
     * @throws ApiException
     */
    public function uploads()
    {
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        $type = $this->request->param('file_type','');
        $saveKey = 'uploads/';
        switch ($type)
        {
            case 0:

                break;
            case 1: //添加保养记录上传的图片
                $saveKey = "uploads/maintain/";
                break;
            case 2://车辆更多信息上传的图片
                $saveKey = "uploads/car/";
                break;
            case 3://商机图片
                $saveKey = "uploads/service/";
                break;
            default:

        }
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload($saveKey.md5(time().rand(1000,9999)));
        } catch (UploadException $e) {
            throw new ApiException($e->getMessage(), 200);
        }
        return $this->response(['url' =>cdnurl($attachment->url, true)]);
    }


    /**
     * 获取所有城市
     * @return array
     * @throws \think\exception\DbException
     */
    public function citys()
    {
        $brands = Amap::field('id,name,city_initial_letter letter')->where(['level'=>2])->select()->toArray();
        //把获取到首字母的数组排序
        $sort="SORT_ASC";
        $brands= arraySequence($brands, "letter",$sort);
        //创建新数组
        $data = [];
        //通过字段相同的分到一个新数组
        foreach($brands as &$v){
            $data[$v['letter']][]=$v;
        }
        return $this->response($data);
    }

    /**
     * 获取指定城市的县/区
     * @return array
     * @throws \think\exception\DbException
     */
    public function districts()
    {
        $city_id = input('city_id','');
        if (empty($city_id))
            throw new ApiException('城市信息未选择',404,0);
        $city = Amap::get($city_id);
        $list = Amap::field('id,name')->where(['level'=>3,'city'=>$city['city']])->select()->toArray();
        return $this->response($list);
    }

    /**
     * 获取指定商机对应的搜索条件
     * @return array
     * @throws \think\exception\DbException
     */
    public function condition()
    {
        $service_type = input('service_type',1);
        switch ($service_type)
        {
            case 1://二手车
                $arr = [
                    ['name'=>'默认排序','type'=>'list','list'=>[
                        ['name'=>'默认排序','key'=>'sort','value'=>0],
                        ['name'=>'最新上架','key'=>'sort','value'=>1],
                        ['name'=>'里程最少','key'=>'sort','value'=>2],
                        ['name'=>'价格最低','key'=>'sort','value'=>3],
                        ['name'=>'车龄最短','key'=>'sort','value'=>4]]
                    ],
                    ['name'=>'品牌','type'=>'url','key'=>'models_id','url'=>Env::get('app.app_host') . "/mini/v1/client/brand"],
                    ['name'=>'归属','type'=>'list','list'=>[
                        ['name'=>'全部','key'=>'belong','value'=>0],
                        ['name'=>'个人','key'=>'belong','value'=>1],
                        ['name'=>'车商','key'=>'belong','value'=>2],
                        ['name'=>'我发布的','key'=>'belong','value'=>3],
                    ]],
                    ['name'=>'更多筛选','type'=>'list','list'=>[
                        ['name'=>'车龄区间（年）','key'=>'car_age','type'=>'between','value'=>[0,2,4,6,8,10,9999]],
                        ['name'=>'价格区间（万元）','key'=>'price','type'=>'between','value'=>[0,2,4,6,8,10,9999]],
                        ['name'=>'里程区间（万公里）','key'=>'mileage','type'=>'between','value'=>[0,2,4,6,8,10,9999]],
                        ['name'=>'车辆级别','type'=>'list','list'=>[
                            ['name'=>'全部','key'=>'level','value'=>0],
                            ['name'=>'小型车','key'=>'level','value'=>1],
                            ['name'=>'中型车','key'=>'level','value'=>2],
                            ['name'=>'大型车','key'=>'level','value'=>3],
                        ]],
                        ['name'=>'能源类别','type'=>'list','list'=>[
                            ['name'=>'全部','key'=>'car_type','value'=>0],
                            ['name'=>'燃油车','key'=>'car_type','value'=>1],
                            ['name'=>'混动车','key'=>'car_type','value'=>2],
                            ['name'=>'电动车','key'=>'car_type','value'=>3],
                        ]],
                    ]],
                ];
                break;
            case 2:
                $arr = [['name'=>'全部','key'=>'sort','value'=>0],['name'=>'搭电/电瓶更换','key'=>'sort','value'=>1],['name'=>'补胎/换胎','key'=>'sort','value'=>2],['name'=>'拖车','key'=>'sort','value'=>3]];
                break;
            default:
                $arr = [['name'=>'默认排序','type'=>'list','list'=>[
                    ['name'=>'最新上架','key'=>'sort','value'=>1],
                    ['name'=>'我发布的','key'=>'sort','value'=>2],
                    ['name'=>'距离优先','key'=>'sort','value'=>3]
                ]]];
        }
        return $this->response($arr);
    }



}
